import Util from "../../common/Util"
import Api from "../../common/Api"

const LOGIN="LOGIN";
const LOGIN_SUCCESS="LOGIN_SUCCESS";
const LOGIN_FAILURE="LOGIN_FAILURE";

const SET_USER="SET_USER";

const initialState={
  user:{},
  token:'',
  expires:0,
  isLogin:false,
}
export default function reducer(state=initialState,action){
  const {type,payload}=action;

  switch (type) {
    case LOGIN_SUCCESS:
      window.localStorage.setItem('token', payload.token);
      return {
        user:payload.user,
        token:payload.token,
        expires:payload.expires,
        isLogin:true
      }
    case LOGIN_FAILURE:
      return{
        user:{},
        isLogin:false
      }
    case SET_USER:
      return Object.assign({},state,{
        user:{...state.user,...payload}
      })
    default:
      return state;
  }
}

export function setUser(user){
  return {
    type:SET_USER,
    payload:user
  }
}
export function login(user){
  const url=Api.user_login;
  return dispatch=>{
     Util.post(url,user,(data)=>{
      if(data.user!==undefined){
          dispatch({
            type:LOGIN_SUCCESS,
            payload:data
          })
      }else{
        dispatch({type:LOGIN_FAILURE,payload:{}})
      }

    });
  }


}
